package com.example.springmvcdemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class BookController {
    @RequestMapping("/test")
    public String test() {
        return "bookForm";
    }

    @RequestMapping("/bookForm")
    public String bookForm(String name, HttpServletRequest request,HttpServletResponse response, MultipartFile pic) throws IOException {
        String filename = "";
        String uploadFileName;
        uploadFileName = pic.getOriginalFilename();
        assert uploadFileName != null;
        String extendsName=uploadFileName.substring(uploadFileName.lastIndexOf(".")+1,uploadFileName.length());
        String uuid= UUID.randomUUID().toString().replace("-","").toUpperCase();
        if(!StringUtils.isEmpty(name)){
            filename=uuid+"-"+name+"."+extendsName;
        }else {
            filename=uuid+"_"+uploadFileName;
        }
        System.out.println(filename);
        ServletContext context = request.getServletContext();
        String path = context.getRealPath("/uploads");
        String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File file = new File(path + "/" + filename);
        if(!file.exists()){
            file.mkdirs();
        }
        pic.transferTo(new File(file,filename));
        return "index";
    }
}
